package com.suhu.admin;

import org.springframework.data.domain.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-12-10
 * Time: 下午8:59
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @RequestMapping(method = RequestMethod.GET)
    public String index() {
        return "admin/index";
    }

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    @ResponseBody
    public Page<User> users(@ModelAttribute Pageable pageable) throws InterruptedException {
        int total = 100;
        List<User> users = createUsers(pageable.getPageNumber(), 10);
        Sort sort = pageable.getSort();
        if (sort != null && sort.iterator().hasNext()) {
            Collections.shuffle(users);
        }
        PageImpl<User> page = new PageImpl<User>(users, pageable, total);
        return page;
    }

    @ModelAttribute("pageable")
    public Pageable getPageable(HttpServletRequest request) {
        Object pageRequest = request.getAttribute("pageRequest");
        return pageRequest == null ? new PageRequest(0, 10) : (Pageable) pageRequest;
    }

    private List<User> createUsers(int pageNumber, int size) {
        ArrayList<User> result = new ArrayList<User>();
        for (int i = pageNumber * size; i < pageNumber * size + size; i++) {
            result.add(new User(String.valueOf(i), "user " + i));
        }
        return result;
    }

    class User {
        public User(String id, String username) {
            this.id = id;
            this.username = username;
        }

        String id;
        String username;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }
    }
}
